import { FC, useContext, useState } from 'react';
import { DragSource } from 'react-dnd';
import { Button, Select } from 'antd';
import { endDrag, beginDrag, sourceCollect } from '@/utils';
import { DesignProvider, DesignRedux } from '../../DesignRedux';
import CheckImgModal from '../../CheckImgModal';
import DragBox from '../../DragBox';

import styles from './index.less';

const { Option } = Select;

const BannerFC: FC<any> = (props: any) => {
  const { property, isDragging, connectDragSource } = props;
  const { comProperty } = property;

  const { state, dispatch } = useContext(DesignRedux);
  const [isModalVisible, setIsModalVisible] = useState(false);

  const onClickShowImgModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onChangeImg = (param: any) => {
    handleCancel();
    // setBgImg(param.img);
    comProperty.imgUrl = param.img;
    const newNodeTree = [...state.nodeTree];
    updNodeItem(newNodeTree, property, comProperty);
    // todo 优化
    dispatch({
      nodeTree: JSON.parse(JSON.stringify(newNodeTree)),
      rightEleProperty: property,
    });
  };

  // 容器组件添加子组件
  function updNodeItem(data: any, node: any, comProperty: any) {
    for (const [index, item] of data.entries()) {
      const { children = [] } = item;
      if (item.id === property.id) {
        item.comProperty = comProperty;
      }
      if (item.id !== property.id && children) {
        updNodeItem(children, node, comProperty);
      }
    }
  }

  return (
    <div ref={connectDragSource}>
      <DragBox property={property}>
        <div
          className={styles.ztBanner}
          style={{
            background: `url(${comProperty.imgUrl}) no-repeat center top`,
          }}
          onClick={onClickShowImgModal}
        />
      </DragBox>
      <CheckImgModal
        visible={isModalVisible}
        onChange={onChangeImg}
        onClose={handleCancel}
      />
    </div>
  );
};

const Banner = DragSource(
  'box',
  {
    beginDrag, // 开始拖动
    endDrag, // 拖动完成
  },
  (connect: any, monitor: any) => sourceCollect(connect, monitor),
)(BannerFC);

export default Banner;
// todo 添加可以拖拽属性
